<template>
  <a-card :bordered="false">
    <search-form
      :showAddButton="false"
      :showSuperButton="false"
      exportFileName="仓库入库审核列表"
      :showColumnNumber="8"
      :searchButtonFun="searchButtonFun"
      :resetButtonFun="resetButtonFun"
    >
      <a-col :xl="4" :lg="7" :md="8" :sm="24">
        <a-form-item label="出库单号">
          <a-input placeholder="请输入出库单号" v-model="queryParam.entryOrderNum" allowClear></a-input>
        </a-form-item>
      </a-col>
      <a-col :xl="4" :lg="7" :md="8" :sm="24">
        <a-form-item label="工单号">
          <a-input v-model="queryParam.moNum" placeholder="请输入工单号" allowClear></a-input>
        </a-form-item>
      </a-col>
      <a-col :xl="4" :lg="7" :md="8" :sm="24">
        <a-form-item label="创建时间">
          <a-range-picker
            format="YYYY-MM-DD"
            :placeholder="['开始日期', '结束日期']"
            valueFormat="YYYY-MM-DD"
            @change="dateChange"
            v-model="createDateRange"
          />
        </a-form-item>
      </a-col>
      <a-col :xl="4" :lg="7" :md="8" :sm="24">
        <a-form-item label="状态">
          <fmsx-select
            placeholder="请输入状态"
            v-model="queryParam.status"
            :data="statusOptions"
            :showSearch="false"
          ></fmsx-select>
        </a-form-item>
      </a-col>
      <a-col :xl="4" :lg="7" :md="8" :sm="24">
        <a-form-item label="客户代码">
          <a-input placeholder="请输入客户代码" v-model="queryParam.custCode" allowClear></a-input>
        </a-form-item>
      </a-col>
      <template #otherButton>
        <a-button :disabled="RejectDisable" type="primary" class="auth-reject" @click="handleRject()"
          >审核不通过</a-button
        >
        <a-button :disabled="!PassDisable" type="primary" @click="handlePass()">确认出库</a-button>
      </template>
    </search-form>

    <div class="fivs-all-box">
      <div class="fivs-all-contain">
        <fmsx-table
          ref="table"
          size="middle"
          rowKey="id"
          :bordered="false"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          isShowOptions
          class="j-table-force-nowrap"
          @change="handleTableChange"
          @expand="expandFun"
          :expandedRowKeys="expandedRowKeys"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <template slot="status" slot-scope="text, record">
            <a-tag :color="getStatusColor(record)">
              {{ record.status_dictText }}
            </a-tag>
          </template>
          <span slot="action" slot-scope="text, record" class="fivs-all-action">
            <a-popover
              v-if="record.status == 10 || record.status == 25"
              placement="top"
              arrow-point-at-center
              overlayClassName="fivs-all-tip"
            >
              <template slot="content"> {{ $t('popover.editTxt') }} </template>
              <div class="fivs-all-btn fivs-all-edit" @click="handleEdit(record)"></div>
            </a-popover>
            <a-popover
              v-if="record.status == 30 || record.status == 40"
              placement="top"
              arrow-point-at-center
              overlayClassName="fivs-all-tip"
            >
              <template slot="content"> {{ $t('popover.infoTxt') }} </template>
              <div
                v-if="record.status != 1"
                class="fivs-all-btn fivs-all-xiangqing"
                @click="handleDetail(record)"
              ></div>
            </a-popover>
            <a-popconfirm title="确定删除吗？" @confirm="handleDelete([{ id: record.id }])">
              <a-popover
                v-if="record.status == 10"
                placement="top"
                arrow-point-at-center
                overlayClassName="fivs-all-tip"
              >
                <template slot="content"> {{ $t('popover.delTxt') }} </template>
                <div class="fivs-all-btn fivs-all-del"></div>
              </a-popover>
            </a-popconfirm>
          </span>
          <div slot="expandedRowRender" class="row-child-table" slot-scope="record">
            <fmsx-table
              ref="table"
              size="middle"
              bordered
              rowKey="id"
              :columns="columnsChild"
              :dataSource="childObj[record.id] ? childObj[record.id].dataSource : []"
              :pagination="false"
              class="j-table-force-nowrap"
              isShowOptions
            >
            </fmsx-table>
          </div>
        </fmsx-table>
      </div>
    </div>
    <OutboundItem
      v-if="isShowInboundItem"
      v-model="isShowInboundItem"
      :applyEntryId="selectedRowKeys"
      @ok="passByWarehouseFun"
    ></OutboundItem>

    <outboundModal ref="modalForm" v-if="isShowAdd" v-model="isShowAdd" disableSubmit></outboundModal>
  </a-card>
</template>
<script>
import wipApi from '@/api/fmsx/wip'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import OutboundItem from './components/OutboundItem.vue'
import outboundModal from './outboundModal.vue'

export default {
  name: 'WarehouseAudit',
  mixins: [JeecgListMixin],
  desc: '入库仓库审核',

  components: { OutboundItem, outboundModal },

  data() {
    return {
      isShowAdd: false,
      isShowInboundItem: false,
      statusOptions: [
        {
          label: '仓库待确认',
          value: 40
        },
        {
          label: '仓库已入库',
          value: 50
        }
      ],
      createDateRange: [],
      url: {
        list: '/prod-pre/make/makeApplyOut/affirm/list',
        exportXlsUrl: '/prod-pre/material/materialEntryOrder/warehouseExport'
      },
      axiosType: 'GET',
      selectedRowKeys: [],
      selectionRows: [],
      visible: false,
      expandedRowKeys: [],
      childObj: {},
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '出库单号',
          align: 'center',
          dataIndex: 'entryNo'
        },
        {
          title: '总数量',
          align: 'center',
          dataIndex: 'outQuantity'
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },

        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark'
        },
        {
          title: this.$t('createBy'),
          align: 'center',
          width: 80,
          dataIndex: 'createBy'
        },
        {
          title: this.$t('createDate'),
          width: 150,
          align: 'center',
          dataIndex: 'createTime'
        },
        {
          title: this.$t('optionsBy'),
          align: 'center',
          width: 80,
          dataIndex: 'updateBy'
        },
        {
          title: this.$t('optionsTime'),
          width: 150,
          align: 'center',
          dataIndex: 'updateTime'
        },
        {
          title: this.$t('options'),
          dataIndex: 'action',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'action' }
        }
      ],
      columnsChild: [
        {
          title: '工单号',
          align: 'center',
          dataIndex: 'moNum'
        },
        {
          title: '工序',
          align: 'center',
          dataIndex: 'operationNum'
        },
        {
          title: '工序编码',
          align: 'center',
          dataIndex: 'processName'
        },
        {
          title: '图号',
          align: 'center',
          dataIndex: 'dwgNo',
          customRender: (text, row, index) => {
            if (text && text.length > 0) {
              //let url = window._CONFIG['domianURL'] + '/base/annex/file/download/' + userpath
              let url = '/#/mes/other/pdf?drawNum=' + row.drawNum + '&drawRev=' + row.drawNumVersion
              return (
                <a href={url} target="_blank">
                  {text}
                </a>
              )
            }
          }
        },
        {
          title: '版本',
          align: 'center',
          dataIndex: 'rev'
        },
        {
          title: '客户代码',
          align: 'center',
          dataIndex: 'custCode'
        },
        {
          title: '数量',
          align: 'center',
          dataIndex: 'outQuantity'
        },
        {
          title: '仓库名称',
          align: 'center',
          dataIndex: 'wmsId_dictText'
        },
        {
          title: '货架名称',
          align: 'center',
          dataIndex: 'shelvesId_dictText'
        },
        {
          title: '储位名称',
          align: 'center',
          dataIndex: 'storageId_dictText'
        }
      ]
    }
  },

  // 10草稿，20部门待审核，25部门驳回，40仓库待确认，45仓库驳回 50仓库已审核，60作废
  computed: {
    RejectDisable() {
      if (this.selectionRows.length == 0) return true
      return this.selectionRows.some((item) => item.status != 20)
    },
    PassDisable() {
      if (this.selectionRows.length == 0) return true
      return this.selectionRows.every((item) => item.status == 20)
    },
    ReflectingTaskDisable() {
      if (this.selectionRows.length == 0) return true
      return this.selectionRows.some((item) => item.status != 50)
    },
    SaveTaskDisable() {
      if (this.selectionRows.length == 0) return true
      return this.selectionRows.some((item) => ![40, 45].includes(item.status))
    }
  },

  methods: {
    handleDetail(record) {
      this.isShowAdd = true
      this.$nextTick(() => {
        this.$refs.modalForm.edit(record)
      })
    },
    getStatusColor(item) {
      let color = 'green'
      switch (item.status) {
        case 10:
          color = ''
          break
        case 30:
          color = 'red'
          break
        case 40:
          color = 'green'
          break
        case 20:
          color = 'blue'
          break
      }
      return color
    },
    expandFun(expanded, record) {
      this.expanded = expanded
      if (expanded) {
        wipApi.outbound.getItemList({ applyOutId: record.id }).then((res) => {
          this.childObj[record.id] = {
            dataSource: res.records
          }
          this.expandedRowKeys.push(record.id)
        })
      } else {
        this.expandedRowKeys.splice(this.expandedRowKeys.indexOf(record.id), 1)
      }
    },
    searchButtonFun() {
      this.onSelectChange([], [])
      this.loadData()
    },
    resetButtonFun() {
      this.queryParam = {}
      this.searchButtonFun()
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },

    handleRject() {
      if (this.selectedRowKeys.length == 0) return this.$message.warning('请勾选需要操作的数据')
      wipApi.outbound.reject({ ids: this.selectedRowKeys.join(',') }).then((res) => {
        this.$message.success(this.$t('tips.optionsTxt'))
        this.loadData()
        this.onSelectChange([], [])
      })
    },
    handlePass() {
      if (this.selectedRowKeys.length > 0) {
        this.isShowInboundItem = true
      } else {
        this.$message.warning('请选择入库项！')
      }
    },
    passByWarehouseFun() {
      this.loadData()
      this.$refs.applyTable.clearSelectChange(false)
      this.onSelectChange([], [])
    },
    handlePrint(type) {
      const list = this.selectionRows
      // 如果是采购入库或者委外入库判断是否同一个供应商 entryType 1 3
      let hasSupplier = false
      const supplierList = []
      const customerList = []
      for (let i = 0; i < list.length; i++) {
        if (list[i].entryType == 1 || list[i].entryType == 3) {
          hasSupplier = true
          supplierList.push(list[i].supplierId)
        } else if (hasSupplier && !list[i].supplierId) {
          return this.$message.warning('请勾选采购入库或委外入库')
        }
        customerList.push(list[i].custCode)
      }
      if (hasSupplier) {
        const set = new Set(supplierList)
        if (set.has('')) return this.$message.warning('请勾选采购入库或委外入库')
        if (set.size > 1) return this.$message.warning('请勾选相同的供应商')
      } else {
        const set = new Set(customerList)
        if (set.size > 1) return this.$message.warning('请勾选相同的客户')
      }
      this.visible = true
      wmsNewApi.inbound.batchPrint({ idList: this.selectedRowKeys }).then((res) => {
        let data = {}
        if (res && res.records && res.records.length > 0) {
          data = { ...res.records[0], supplierName: res.records[0].supplierId_dictText }
        }
        this.$refs.enterBound.setData(data, type)
      })
    },

    onPrint() {
      this.$refs.enterBound.onPrint()
    },

    dateChange(e) {
      this.queryParam.createStartDate = e[0] || ''
      this.queryParam.createEndDate = e[1] || ''
    }
  }
}
</script>
<style lang="less" scoped></style>
